import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '@/utils/request'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref({})
  
  const login = async (data) => {
    const res = await request.post('/auth/login', data)
    token.value = res.token
    localStorage.setItem('token', res.token)
    await getUserInfo()
  }
  
  const getUserInfo = async () => {
    const res = await request.get('/user/info')
    userInfo.value = res
  }
  
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
  }
  
  return {
    token,
    userInfo,
    login,
    getUserInfo,
    logout
  }
}) 